package se.topshelf.golftracker.web.controller.teebox;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import se.topshelf.golftracker.core.domain.Hole;
import se.topshelf.golftracker.core.domain.TeeBox;
import se.topshelf.golftracker.core.domain.TeeColour;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.CourseService;
import se.topshelf.golftracker.web.controller.BaseEntityController;
import se.topshelf.golftracker.web.editor.BaseEntityEditor;

import javax.annotation.Resource;

/**
 *
 */
@Controller
@SessionAttributes({"entity", "hole"})
@RequestMapping("/teebox")
public class TeeBoxController extends BaseEntityController<TeeBox> {
    public static final String TEE_BOX_CONTEXT_PATH = "teebox";
    @Resource  // Automatically set ("wired") by Spring
    private CourseService courseService;
    private static final String ALL_TEE_COLOURS_MODEL_ATTRIBUTE = "allTeeColours";

    public TeeBoxController() {
        super(TeeBox.class);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Hole.class, new BaseEntityEditor<Hole>(Hole.class, courseService));
    }

    @Override
    protected void doAddParentToModel(ModelMap model, String parentId) {
        Hole hole = courseService.get(Hole.class, parentId);
        if(hole != null) {
            model.addAttribute("hole", hole);
        } else{
            throw new IllegalArgumentException("Tried to create a new tee box without attaching it to a Course");
        }
    }

    @Override
    protected String getRedirectAfterSavePath(TeeBox savedEntity) {
        return "redirect:" + "/hole/view.htm?id=" + savedEntity.getHole().getId();
    }

    @Override
    protected Validator getValidator() {
        return new TeeBoxValidator(courseService);
    }

    @Override
    protected String getEntityUrlContextPath() {
        return TEE_BOX_CONTEXT_PATH;
    }

    @Override
    protected BaseService getBaseService() {
        return courseService;
    }

    @Override
    protected void addModelReferenceData(ModelMap model, TeeBox entity) {
        model.put(ALL_TEE_COLOURS_MODEL_ATTRIBUTE, TeeColour.getAllTeeColours());
    }
}
